//
//  ZOAuthViewController.swift
//  swift-weibo
//
//  Created by zero on 17/3/23.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

class ZOAuthViewController: UIViewController {

    
    let webView = UIWebView()
    
    
    override func loadView() {
        
        view = webView
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = URL(string: urlString)
        
        let request = URLRequest(url: url!)
        
        webView.loadRequest(request)
        
        webView.delegate = self
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "", target: self, action:#selector(back))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", imageName: "", target: self, action: #selector(jsonInWeb))
    }

    //  返回
    @objc private func back(){
        
        dismiss(animated: true, completion: nil)
    }
    
    //  json注入
    @objc private func jsonInWeb(){
        
        let jsString = "document.getElementById('userId').value = '18875015218' , document.getElementById('passwd').value = 'jllJLL940424'"
        webView.stringByEvaluatingJavaScript(from: jsString)

    }
    
    


}

extension ZOAuthViewController : UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        print("开始解析")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        print("结束解析")
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.url?.absoluteString
        
        let flag = "http://www.baidu.com/?code="
        
        if (url?.contains(flag))! {
            
            let code = url?.substring(from: flag.endIndex)
            
            ZUserAccountViewModel.shareUserAccoutn.getToken(code: code!, finish: { (res) in
                
                if res {
                    
                    print("成功")
                    
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: ChangeVC), object: changVC.mainTab)
                    
                }else{
                    print("失败")
                }
                
            })
            
            return false
        }
        
        
        return true
    }
}
